<template>
  <div class="app-container">
    <el-form v-show="showSearch" ref="queryForm" :inline="true" :model="queryParams" label-width="68px" size="small">
      <el-form-item label="创建时间" prop="jhCreatedTime">
        <el-date-picker v-model="queryParams.jhCreatedTime" clearable placeholder="请选择创建时间" type="date" value-format="yyyy-MM-dd"></el-date-picker>
      </el-form-item>
      <el-form-item label="模版名称" prop="jhTemplateName">
        <el-input v-model="queryParams.jhTemplateName" clearable placeholder="请输入模版名称" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item label="商家编码" prop="jhCode">
        <el-input v-model="queryParams.jhCode" clearable placeholder="请输入商家编码" @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button icon="el-icon-search" size="mini" type="primary" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button v-hasPermi="['jihuo:template:add']" icon="el-icon-plus" plain size="mini" type="primary" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['jihuo:template:edit']" :disabled="single" icon="el-icon-edit" plain size="mini" type="success" @click="handleUpdate">修改</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['jihuo:template:remove']" :disabled="multiple" icon="el-icon-delete" plain size="mini" type="danger" @click="handleDelete">删除</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button v-hasPermi="['jihuo:template:export']" icon="el-icon-download" plain size="mini" type="warning" @click="handleExport">导出</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="templateList" @selection-change="handleSelectionChange">
      <el-table-column align="center" type="selection" width="55"/>
      <el-table-column align="center" label="序号" prop="items" width="55">
        <template #default="scope">
          {{ scope.$index + 1 }}
        </template>
      </el-table-column>
      <el-table-column align="center" label="模板编号" prop="jhId" width="180"/>
      <el-table-column align="center" label="创建时间" prop="jhCreatedTime" width="180">
        <template slot-scope="scope">
          <span>{{ parseTime(scope.row.jhCreatedTime, '{y}-{m}-{d}') }}</span>
        </template>
      </el-table-column>
      <el-table-column align="center" label="模版名称" prop="jhTemplateName"/>
      <el-table-column align="center" label="商家编码" prop="jhCode"/>
      <el-table-column align="center" class-name="small-padding fixed-width" label="操作">
        <template slot-scope="scope">
          <el-button
            v-hasPermi="['jihuo:template:edit']"
            icon="el-icon-edit"
            size="mini"
            type="text"
            @click="handleUpdate(scope.row)"
          >修改
          </el-button>
          <el-button
            v-hasPermi="['jihuo:template:remove']"
            icon="el-icon-delete"
            size="mini"
            type="text"
            @click="handleDelete(scope.row)"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination v-show="total>0" :limit.sync="queryParams.pageSize" :page.sync="queryParams.pageNum" :total="total" @pagination="getList"/>

    <!-- 添加或修改模板配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" append-to-body width="900px">
      <el-form ref="elForm" :model="form" :rules="rules" label-width="80px">
        <div class="app-container">
          <el-tabs v-model="activeName" @tab-click="handleClick">
            <el-tab-pane label="基础设置" name="jcsz">
              <jcsz ref="jcsz"></jcsz>
            </el-tab-pane>
            <el-tab-pane label="商品过滤" name="spgl">
              <spgl ref="spgl"></spgl>
            </el-tab-pane>
            <el-tab-pane label="图片/视频设置" name="jdvcGoods">
              <imageSetting ref="imageSetting"></imageSetting>
            </el-tab-pane>
          </el-tabs>

        </div>
      </el-form>
      <div slot="footer" center class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import "splitpanes/dist/splitpanes.css";
import {addTemplate, delTemplate, getTemplate, listTemplate, updateTemplate,getTeFiCa} from "@/api/jihuo/template";
import spgl from "@/views/jihuo/template/spgl";
import jcsz from "@/views/jihuo/template/jcsz";
import imageSetting from "@/views/jihuo/template/imageSetting";

export default {
  components: {jcsz, spgl, imageSetting},
  name: "Template",
  data() {
    return {
      typeList: [],
      activeName: 'jcsz',
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 模板配置表格数据
      templateList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        jhRevision: null,
        jhCreatedBy: null,
        jhCreatedTime: null,
        jhUpdatedBy: null,
        jhUpdatedTime: null,
        jhTemplateName: null,
        jhCode: null,
        jhPurchaseAddress: null,
        jhShippingAddress: null,
        jhPrefix: null,
        jhSuffix: null,
        jhDelContent: null,
        jhString001: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        jhRevision: [
          {required: true, message: "乐观锁不能为空", trigger: "blur"}
        ],
        jhCreatedBy: [
          {required: true, message: "创建人不能为空", trigger: "blur"}
        ],
        jhCreatedTime: [
          {required: true, message: "创建时间不能为空", trigger: "blur"}
        ],
        jhUpdatedBy: [
          {required: true, message: "更新人不能为空", trigger: "blur"}
        ],
        jhUpdatedTime: [
          {required: true, message: "更新时间不能为空", trigger: "blur"}
        ],
        jhTemplateName: [
          {required: true, message: "模版名称不能为空", trigger: "blur"}
        ],
        jhCode: [
          {required: true, message: "商家编码不能为空", trigger: "blur"}
        ],
      },
      items: ['1', '2', '3', '4', '5', '6', '7', '8', '9', '10']
    };
  },
  created() {
    this.getList();
  },
  mounted() {
    this.activeName = 'jcsz';
    // 初始化时同步数据到子组件
    this.$refs.jcsz?.setData(this.form);
    this.$refs.spgl?.setData(this.form);
    this.$refs.imageSetting?.setData(this.form);
  },
  methods: {
    /** 查询模板配置列表 */
    getList() {
      this.loading = true;
      listTemplate(this.queryParams).then(response => {
        this.templateList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
      this.$nextTick(() => {
        this.$refs.jcsz?.reset();
        this.$refs.spgl?.reset();
        this.$refs.imageSetting?.reset();
      });
    },
    // 表单重置
    reset() {
      this.form = {};
      this.$refs.elForm && this.$refs.elForm.resetFields(); // 重置主表单
      this.$nextTick(() => { // 确保DOM更新后调用子组件
        this.$refs.jcsz?.reset();
        this.$refs.spgl?.reset();
        this.$refs.imageSetting?.reset();
      });
    },
    resetForm() {
      this.$refs['queryForm'].resetFields()
      // this.$refs['jcsz'].resetFields()
      // this.$refs['spgl'].resetFields()
      // this.$refs['imageSetting'].resetFields()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm();
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.jhId)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset(); // 新增：调用重置方法
      this.open = true;
      this.title = "添加模板配置";
      this.activeName = 'jcsz'; // 确保模态框打开时默认显示jcsz页面
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      const jhId = row.jhId || this.ids;
      getTemplate(jhId).then(response => {
        // 先重置，确保清空之前的数据
        this.reset();

        // 设置表单数据
        this.form = response.data;
        this.open = true;
        this.title = "修改模板配置";
        this.activeName = 'jcsz';

        // 使用nextTick确保弹窗完全打开后再同步数据
        this.$nextTick(() => {
          // 再次确保DOM完全更新后同步数据
          this.$nextTick(() => {
            // 添加延时确保所有子组件完全挂载
            setTimeout(() => {
              if (this.$refs.jcsz) {
                this.$refs.jcsz.setData(this.form);
              }
              if (this.$refs.spgl) {
                this.$refs.spgl.setData(this.form);
              }
              if (this.$refs.imageSetting) {
                this.$refs.imageSetting.setData(this.form);
              }
            }, 100); // 100ms延时确保组件完全就绪
          });
        });
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["elForm"].validate(valid => {
        if (valid) {
          // 使用可选链操作符防止未定义错误
          const jcszData = this.$refs.jcsz?.getFormData() || {};
          const spglData = this.$refs.spgl?.getFormData() || {};
          const imageSettingData = this.$refs.imageSetting?.getFormData() || {};
          console.log(jcszData);
          console.log(spglData);

          console.log(jcszData);
          console.log(spglData);

          // 合并所有组件数据
          this.form = {
            ...this.form,
            ...(imageSettingData || {}),
            ...(spglData || {}),
            ...(jcszData || {}),
          };
          console.log(this.form);
          if (this.form.jhId != null) {
            updateTemplate(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addTemplate(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const jhIds = row.jhId || this.ids;
      this.$modal.confirm('是否确认删除模板配置编号为"' + jhIds + '"的数据项？').then(function () {
        return delTemplate(jhIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('jihuo/template/export', {
        ...this.queryParams
      }, `template_${new Date().getTime()}.xlsx`)
    },
    /** 页签跳转 */
    handleClick(tab, event) {
      console.log(tab, event);
    }
  }
};
</script>
